﻿//uiController.js

import * as morseCore from './morseCore.js';
import { validateInt, generateRandomGroups } from './utils.js';

// UI元素引用
let elements = {};

/**
 * 初始化UI元素
 */
function initElements() {
    elements = {
        inputText: document.getElementById('inputText'),
        playButton: document.getElementById('playButton'),
        resetButton: document.getElementById('resetButton'),
        morseCircle: document.getElementById('morseCircle'),
        speedValue: document.getElementById('speedValue'),
        callButton: document.getElementById('callButton'),
        endButton: document.getElementById('endButton'),
        randomButton: document.getElementById('randomButton'),
        randomDialog: document.getElementById('randomDialog'),
        decreaseBtn: document.getElementById('decreaseBtn'),
        increaseBtn: document.getElementById('increaseBtn'),
        groupCount: document.getElementById('groupCount'),
        letterBtn: document.getElementById('letterBtn'),
        mixedBtn: document.getElementById('mixedBtn'),
        cancelBtn: document.getElementById('cancelBtn'),
        settingsButton: document.getElementById('settingsButton'),
        settingsDialog: document.getElementById('settingsDialog'),
        speedDecreaseBtn: document.getElementById('speedDecreaseBtn'),
        speedIncreaseBtn: document.getElementById('speedIncreaseBtn'),
        speedInput: document.getElementById('speedInput'),
        settingsConfirmBtn: document.getElementById('settingsConfirmBtn'),
        settingsCancelBtn: document.getElementById('settingsCancelBtn'),
        lightModeSelect: document.getElementById('lightModeSelect'),
        lightModeValue: document.getElementById('lightModeValue')
    };
}

/**
 * 更新UI状态
 */
export function updateUIState() {
    // 更新按钮状态
    if (morseCore.state.isAnimationPlaying) {
        elements.playButton.textContent = '停止';
        elements.playButton.style.backgroundColor = '#c62828';
        elements.inputText.disabled = true;
    } else {
        elements.playButton.textContent = '播放';
        elements.playButton.style.backgroundColor = '#2E7D32';
        elements.inputText.disabled = false;
    }
    
    // 更新码速显示
    elements.speedValue.textContent = morseCore.state.codeSpeed;
    
    // 更新灯光模式显示
    elements.lightModeValue.textContent = 
        morseCore.state.lightMode === morseCore.LIGHT_MODE_SCREEN ? '屏幕' : '闪光灯';
}

/**
 * 播放动画序列
 */
export function playAnimation() {
    if (morseCore.state.isAnimationPlaying || !morseCore.state.animationSequence.length) return;
    
    morseCore.state.isAnimationPlaying = true;
    updateUIState();
    
    let index = 0;
    
    function processNext() {
        if (index >= morseCore.state.animationSequence.length) {
            morseCore.state.isAnimationPlaying = false;
            updateUIState();
            // 确保灯光关闭
            if (morseCore.state.lightMode === morseCore.LIGHT_MODE_SCREEN) {
                elements.morseCircle.style.backgroundColor = 'black';
            } else {
                morseCore.controlFlashlight('dark').catch(() => updateUIState());
            }
            return;
        }
        
        const action = morseCore.state.animationSequence[index++];
        const { state, duration } = action;
        
        // 根据模式控制灯光
        if (morseCore.state.lightMode === morseCore.LIGHT_MODE_SCREEN) {
            elements.morseCircle.style.backgroundColor = state === 'light' ? 'white' : 'black';
        } else {
            morseCore.controlFlashlight(state).catch(() => updateUIState());
        }
        
        morseCore.state.animationTimer = setTimeout(processNext, duration);
    }
    
    // 开始前确保初始状态
    if (morseCore.state.lightMode === morseCore.LIGHT_MODE_SCREEN) {
        elements.morseCircle.style.backgroundColor = 'black';
    } else {
        morseCore.controlFlashlight('dark').catch(() => updateUIState());
    }
    
    processNext();
}

/**
 * 停止动画播放
 */
function stopAnimation() {
    clearTimeout(morseCore.state.animationTimer);
    morseCore.state.isAnimationPlaying = false;
    updateUIState();
    
    // 确保灯光关闭
    if (morseCore.state.lightMode === morseCore.LIGHT_MODE_SCREEN) {
        elements.morseCircle.style.backgroundColor = 'black';
    } else {
        morseCore.controlFlashlight('dark').catch(() => updateUIState());
    }
}

/**
 * 初始化事件监听器
 */
export function initEventListeners() {
    // 强制输入框内容大写
    elements.inputText.addEventListener('input', function() {
        this.value = this.value.toUpperCase();
    });
    
    // 播放/停止按钮
    elements.playButton.addEventListener('click', function() {
        if (morseCore.state.isAnimationPlaying) {
            stopAnimation();
            return;
        }
        
        const text = morseCore.validateInput(elements.inputText);
        if (!text) return;
        
        morseCore.generateAnimation(text);
        elements.morseCircle.style.backgroundColor = 'black';
        playAnimation();
    });
    
    // 清空按钮
    elements.resetButton.addEventListener('click', function() {
        stopAnimation();
        elements.inputText.value = '';
        elements.inputText.focus();
        elements.morseCircle.style.backgroundColor = 'black';
    });
    
    // 勤务符号按钮
    elements.callButton.addEventListener('click', () => {
        morseCore.insertSpecialSymbol(elements.inputText, '[CALL]');
    });
    
    elements.endButton.addEventListener('click', () => {
        morseCore.insertSpecialSymbol(elements.inputText, '[END]');
        elements.inputText.blur();
    });
    
    // 乱码对话框控制
    elements.randomButton.addEventListener('click', () => {
        elements.randomDialog.style.display = 'flex';
    });
    
    elements.cancelBtn.addEventListener('click', () => {
        elements.randomDialog.style.display = 'none';
    });
    
    // 乱码组数控制
    elements.decreaseBtn.addEventListener('click', function() {
        elements.groupCount.value = Math.max(parseInt(elements.groupCount.value) - 1, 1);
        validateInt(elements.groupCount, 1, 50, 10);
    });
    
    elements.increaseBtn.addEventListener('click', function() {
        elements.groupCount.value = Math.min(parseInt(elements.groupCount.value) + 1, 50);
        validateInt(elements.groupCount, 1, 50, 10);
    });
    
    // 乱码组数范围验证
    elements.groupCount.addEventListener('blur', () => {
        validateInt(elements.groupCount, 1, 50, 10);
    });
    
    // 乱码生成按钮事件
    elements.letterBtn.addEventListener('click', () => {
        const randomGroups = generateRandomGroups('letter', parseInt(elements.groupCount.value));
        elements.inputText.value = randomGroups;
        elements.inputText.focus();
        elements.inputText.setSelectionRange(randomGroups.length, randomGroups.length);
        elements.randomDialog.style.display = 'none';
        elements.inputText.blur();
    });
    
    elements.mixedBtn.addEventListener('click', () => {
        const randomGroups = generateRandomGroups('mixed', parseInt(elements.groupCount.value));
        elements.inputText.value = randomGroups;
        elements.inputText.focus();
        elements.inputText.setSelectionRange(randomGroups.length, randomGroups.length);
        elements.randomDialog.style.display = 'none';
        elements.inputText.blur();
    });
    
    // 设置功能
    elements.settingsButton.addEventListener('click', () => {
        elements.speedInput.value = morseCore.state.codeSpeed;
        elements.lightModeSelect.value = morseCore.state.lightMode;
        elements.settingsDialog.style.display = 'flex';
    });
    
    elements.speedDecreaseBtn.addEventListener('click', () => {
        elements.speedInput.value = Math.max(parseInt(elements.speedInput.value) - 1, 15);
        validateInt(elements.speedInput, 15, 60, 45);
    });
    
    elements.speedIncreaseBtn.addEventListener('click', () => {
        elements.speedInput.value = Math.min(parseInt(elements.speedInput.value) + 1, 60);
        validateInt(elements.speedInput, 15, 60, 45);
    });
    
    elements.settingsConfirmBtn.addEventListener('click', async () => {
        const newSpeed = parseInt(elements.speedInput.value);
        const newLightMode = elements.lightModeSelect.value;
        
        // 处理闪光灯模式切换
        if (newLightMode === morseCore.LIGHT_MODE_FLASHLIGHT && 
            morseCore.state.lightMode !== morseCore.LIGHT_MODE_FLASHLIGHT) {
            const success = await morseCore.initializeFlashlight();
            if (!success) {
                alert('无法访问闪光灯，已切换为屏幕模式');
                elements.lightModeSelect.value = morseCore.LIGHT_MODE_SCREEN;
                newLightMode = morseCore.LIGHT_MODE_SCREEN;
            }
        } else if (newLightMode !== morseCore.LIGHT_MODE_FLASHLIGHT && 
                   morseCore.state.lightMode === morseCore.LIGHT_MODE_FLASHLIGHT && 
                   morseCore.state.flashlightStream) {
            morseCore.state.flashlightStream.getTracks().forEach(t => t.stop());
            morseCore.state.flashlightStream = null;
        }
        
        morseCore.state.lightMode = newLightMode;
        morseCore.state.codeSpeed = newSpeed;
        updateUIState();
        elements.settingsDialog.style.display = 'none';
    });
    
    elements.settingsCancelBtn.addEventListener('click', () => {
        elements.settingsDialog.style.display = 'none';
    });
    
    // 页面可见性变化
    document.addEventListener('visibilitychange', async () => {
        if (document.visibilityState === 'visible') {
            await morseCore.requestWakeLock();
        }
    });
    
    // 页面关闭前清理资源
    window.addEventListener('beforeunload', () => {
        // 释放唤醒锁
        morseCore.releaseWakeLock();
        
        // 释放闪光灯资源
        if (morseCore.state.flashlightStream) {
            morseCore.state.flashlightStream.getTracks().forEach(t => t.stop());
            morseCore.state.flashlightStream = null;
        }
        
        // 确保屏幕灯光关闭
        elements.morseCircle.style.backgroundColor = 'black';
    });
}

/**
 * 初始化UI控制器
 */
export function initUIController() {
    initElements();
    updateUIState();
    initEventListeners();
}
